<template>
  <div class="view">
    <div class="usertop flexb">
      <span class="flex title"><i class="iconfont icon-jiaoyi1 fontcd mr5 c6 title"></i> {{$t('myWallet.buyOrSellRam')}}</span>
    </div>
    <div class="ram">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-button class="btn plain" type="success" plain
            :class="{'blur-btn': activeIndex === 2}"
            @click="activeIndex = 1">{{$t('myWallet.buy')}}</el-button>
        </el-col>
        <el-col :span="12"><el-button class="btn" type="danger" plain
          :class="{'blur-btn': activeIndex === 1}"
          @click="activeIndex = 2">{{$t('myWallet.sell')}}</el-button></el-col>
        <el-col :span="24">
          <div class="gray pd8px">{{$t('myWallet.nowRamPrice')}}{{ ramPrice }} EOS/KB</div>
        </el-col>
      </el-row>
      <!-- 买入 -->
      <div class="buy" v-if="activeIndex === 1">
        <div class="data">
          <el-input type="number" v-model="buy" @change="handleInputBuy" step="0.0001" min="0.0001">
            <template slot="append">EOS</template>
          </el-input>
          <span class="balance fr pd8px gray">{{$t('myWallet.balance')}}：{{ eosBalance }}</span>
        </div>
        <!-- 百分比 -->
        <div class="percent">
          <el-radio-group v-model="percent" @change="handlePercent">
            <el-radio-button label="0.25" style="width:25%">25%</el-radio-button>
            <el-radio-button label="0.5" style="width:25%">50%</el-radio-button>
            <el-radio-button label="0.75" style="width:25%">75%</el-radio-button>
            <el-radio-button label="1" style="width:25%">100%</el-radio-button>
          </el-radio-group>
          <div class="pd8px gray">{{$t('myWallet.planBuy')}}：{{ expectBuy }} KB</div>
          <el-button class="btn" type="success" @click="handleBuyRam">{{$t('myWallet.sureBuy')}}</el-button>
        </div>
      </div>
      <!-- 卖出 -->
      <div  v-if="activeIndex === 2">
        <el-form :model="ruleSell" status-icon :rules="rules" ref="sellForm" class="demo-ruleForm">
          <div class="data">
            <el-form-item prop="sell">
              <el-input type="number" v-model="ruleSell.sell" @change="handleInputSell"  step="0.01" min="0.01">
                <template slot="append">KB</template>
              </el-input>
            </el-form-item>
            <span class="balance fr pd8px gray" style="margin-top: -24px;">{{$t('myWallet.ableRamBalance')}}：{{ ramBalance }} KB</span>
          </div>
          <!-- 百分比 -->
          <div class="percent">
            <el-radio-group v-model="sellPercent" @change="handleSellPercent">
              <el-radio-button label="0.25" style="width:25%">25%</el-radio-button>
              <el-radio-button label="0.5" style="width:25%">50%</el-radio-button>
              <el-radio-button label="0.75" style="width:25%">75%</el-radio-button>
              <el-radio-button label="1" style="width:25%">100%</el-radio-button>
            </el-radio-group>
            <div class="pd8px gray">{{$t('myWallet.planSell')}}：{{ expectSell }} EOS</div>
            <!-- <el-button type="primary" @click="submitForm('sellForm')">提交</el-button> -->
            <el-button class="btn" type="danger" @click="handleSellRam('sellForm')">{{$t('myWallet.sureSell')}}</el-button>
          </div>
        </el-form>
      </div>
    </div>
    <div class="tip gray">
      <div class="pd8px">· {{$t('myWallet.ramTip1')}}</div>
      <div class="">· {{$t('myWallet.ramTip2')}}</div>
      <div class="pd8px">· {{$t('myWallet.ramTip3')}}</div>
    </div>
  </div>
</template>

<script>
// EOS 账户文件
import { EosModel } from '@/utils/eos';
import { toFixed } from '@/utils/validate';

export default {
  data() {
    const sellRules = (rule, value, callback) => {
      if (value === '' || value < 0.02) {
        callback(new Error('卖出量不小于0.02KB'));
      } else {
        callback();
      }
    };
    return {
      percent: '', // 百分比
      sellPercent: '',
      activeIndex: 1, // 买入 / 卖出
      ramBalance: 0, // ram 可交易余额
      expectBuy: 0, // 预计买入
      expectSell: 0, // 预计卖出
      ramPrice: 0, // 当前ram价格

      // 交易数据
      buy: '', // 买入
      ruleSell: {
        sell: '', // 卖出
      },

      timerPrice: null, // 定时器

      rules: {
        sell: [
          { validator: sellRules, trigger: 'blur' },
        ]
      }
    }
  },
  props: {
    totalResources: {
      type: Object,
      default: null,
    },
    eosBalance: {
      type: String,
      default: '0.0000 EOS'
    },
    symbolScience: {
      type: String,
      default: 'EOS'
    },
  },
  watch: {
    totalResources: function change() {
      this.handleGetInfo();
    },
    // 买入量改变
    buy: function listen(newVal) {
      this.expectBuy = toFixed((newVal / this.ramPrice), 2);
    },
    // ram实时价格改变
    ramPrice: function listen(newVal) {
      this.expectBuy = toFixed((this.buy / newVal), 2);
      this.expectSell = toFixed((this.ruleSell.sell * this.ramPrice), 4);
    },
    // 卖出量改变
    'ruleSell.sell': function listen(newVal) {
      this.expectSell = toFixed((newVal * this.ramPrice), 4);
    }
  },
  created() {
  },
  mounted() {
    document.title = this.$t(`rout.${this.$route.meta.title}`);
    this.handleGetInfo();
    this.handleRamPrice();
  },
  beforeDestroy() {
    if (this.timerPrice) {
      clearTimeout(this.timerPrice);
    }
  },
  methods: {
    handleInputBuy(str) {
      this.buy = toFixed(Number(str), 4);
    },
    handleInputSell(str) {
      this.ruleSell.sell = toFixed(Number(str), 2);
    },
    // 获取账户信息
    handleGetInfo() {
      const result = this.totalResources;
      if (result) {
        const ram = result.ram_quota - result.ram_usage;
        this.ramBalance = toFixed((ram / 1024), 2);
      }
    },
    // 百分比买入
    handlePercent(data) {
      const eosBalance = parseFloat(this.eosBalance);
      this.buy = toFixed((eosBalance * data), 4);
    },
    // 百分比卖出
    handleSellPercent(data) {
      const ramBalance = parseFloat(this.ramBalance);
      this.ruleSell.sell = toFixed((ramBalance * data), 2);
    },
    handleBuyRam() {
      // 买入RAM
      if (isNaN(this.buy) || this.buy === '' || this.buy === '0.0000') {
        this.$message.error(this.$t('public.inputRightNum'));
        return;
      }
      if (parseFloat(this.buy) > parseFloat(this.eosBalance)) {
        this.$message.error(this.$t('jy.error3'));
        return;
      }
      const arr = [this.buy];
      arr.push(this.symbolScience);
      const params = arr.join(' ');
      EosModel.eosBuyram(params, (res) => {
        if (res.processed) { // 买入RAM成功
          this.$message.success(this.$t('public.buySuccess'));
          this.buy = '';
          this.$emit('listenGetAccount');
          return
        }
        EosModel.handleScatterErrorBack(res);
      });
    },
    // 卖出RAM
    handleSellRam(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        }
        const bytes = window.parseInt(this.ruleSell.sell * 1024);
        EosModel.eosSellram(bytes, (res) => {
          if (res.processed) { // 买入RAM成功
            this.$message.success(this.$t('public.sellSuccess'));
            this.ruleSell.sell = '';
            // 获取账户明细
            this.$emit('listenGetAccount');
            return
          }
          EosModel.handleScatterErrorBack(res);
        });
        return true;
      });
    },
    // RAM 价格 - 1s 调用一次
    handleRamPrice() {
      EosModel.getRamPrice((price) => {
        if (!price.code) {
          this.ramPrice = Number(price.toFixed(4));
        }
        this.timerPrice = setTimeout(() => {
          this.handleRamPrice();
        }, 1000);
      });
    },
  },
}
</script>

<style scoped lang="scss">
@import '@/views/myWallet/user.scss';
@import '@/assets/css/variables.scss';
@import '@/views/myWallet/eosResource/resource.scss';
.view{
  /deep/ .el-form-item__error{
    margin-top: 8px;
  }
}
</style>
